<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use zgldh\QiniuStorage\QiniuStorage;
use App\ShopArticle;
use App\Article;
use App\Shop;
use App\Type;
use DB;
use Input;

class ShopArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
       //三表查询
       $datas = DB::table('shops_article')->select('shops_article.*','type.typename','shops.shopname')
       ->leftjoin('type','type.typeid','=','shops_article.typeid')
       ->leftjoin('shops','shops.shopid','=','shops_article.shopid')
       ->where('shops_article.aid',$id)
       ->first();
       return view('admin.shoparticle.show',compact('datas'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //获取所有的分类
        $tdatas = Type::select('typeid','typename')->get();
        //根据id查询出所有的数据
        $datas = ShopArticle::where('aid',$id)->select('*')->first();
        return view('admin.shoparticle.edit',compact('datas','tdatas'));

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //进行验证
        $this -> validate($request,[
            'title'=>'required|max:200',
            'keyword'=>'max:200',
            'description'=>'required|max:250',
        ],[
            'title.required'=>'标题不能为空',
            'title.max'=>'标题长度过长',
            'keyword.max'=>'关键字过多',
            'description.required'=>'描述不能为空',
            'description.max'=>'描述字数过多',
        ]);
        //然后接受数据
        $typeid =  trim(Input::get('typeid'));
        $title = Input::get('title');
        $keyword = Input::get('keyword');
        $description = Input::get('description');
        $status = Input::get('status');
        $content = Input::get('content');
        $oldcoverpic = Input::get('oldcoverpic');
        //首先判断有木有图片传来，如果没有，这直接更新
        if(!($request -> hasFile('file'))){
            //执行更新
            $res = ShopArticle::where('aid',$id)->update(['typeid'=>$typeid,'title'=>$title,'description'=>$description,'keyword'=>$keyword,'content'=>$content,'status'=>$status]);
            if($res)
            return back() -> with(['info'=>'更新成功']);
            return back() -> with(['info'=>'更新失败']);
        }else {
            $file = Input::file('file');
            $extension = $file->getClientOriginalExtension();
            $extension = strtolower($extension);
            if (!in_array($extension, ['png', 'jpg']))
                return back()->with(['info' => '需要png类型或者jpg类型']);
            //获取其他扩展名
            $clientName = $file->getClientOriginalName();
            $disk = QiniuStorage::disk('qiniu');
            //删除七牛图片,然后再存入图片
            $newcoverpic = 'article/coverpic/' . md5(date('Y-m-d H:i:s') . $clientName) . "." . $extension;
            $bool = $disk->put($newcoverpic, file_get_contents($file->getRealPath()));
            if ($bool) {
                //获取内容
                $oldcontent = ShopArticle::where('aid', $id)->value('content');
                $pattern = "/<[img|IMG].*?src=[\'|\"].*?(article(.*?)(?:[\.gif|\.jpg|\.png|\/jpeg]))[\'|\"].*?[\/]?>/";
                preg_match_all($pattern, $oldcontent, $match);
                //循环删除
                foreach ($match['1'] as $k => $v) {
                    $bool = $disk->delete($v);
                }
                $res = ShopArticle::where('aid',$id)->update(['typeid'=>$typeid,'title'=>$title,'coverpic'=>$newcoverpic,'description'=>$description,'keyword'=>$keyword,'content'=>$content,'status'=>$status]);

                $delete = $disk->delete($oldcoverpic);
                if($delete)
                return back() -> with(['info' => '更新成功']);
                return back() -> with(['info' => '更新成功，原图片删除失败,地址是:'.$oldcoverpic]);
            }
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //执行删除，获取内容里面的图片；利用正则删除
        $datas = ShopArticle::where('aid',$id)->first();
        //当前文章的封面图片
        $coverpic = $datas['coverpic'];
        //正则提取对应的图片
        $res = ShopArticle::where('aid',$id)->delete();
        if($res) {
            $disk = QiniuStorage::disk('qiniu');
            $content = $datas['content'];
            $pattern = "/<[img|IMG].*?src=[\'|\"].*?(article(.*?)(?:[\.gif|\.jpg|\.png|\/jpeg]))[\'|\"].*?[\/]?>/";
            preg_match_all($pattern, $content, $match);
            //循环删除
            foreach ($match['1'] as $k => $v) {
                $bool = $disk->delete($v);
            }
            $bool = $disk->delete($datas['coverpic']);
            if ($bool) {
                return Response()->json(['status' => 'success', 'msg' => '删除成功']);
            } else {
                return Response()->json(['status' => 'success', 'msg' => '删除七牛图片失败地址:' . $coverpic]);
            }
        }else{
                return Response() -> json(['status'=>'error','msg'=>'删除失败']);
            }

    }
}
